﻿CREATE PROCEDURE [dbo].[sp_Users]
@CSVDomainList NVARCHAR (MAX), @LdapQueryFilter NVARCHAR (MAX)
AS
BEGIN
	DECLARE @Delimiter NVARCHAR(1)
	SET @Delimiter = ','

	DECLARE @QueryString NVARCHAR(MAX)
	SET @QueryString = ''
	DECLARE @CurrentDomain NVARCHAR(MAX), @DomainNamingContext NVARCHAR(MAX)

	--TODO:  Handle null parameters
	WHILE (Charindex(@Delimiter, @CSVDomainList)>0)
	BEGIN
		SET @CurrentDomain = ltrim(rtrim(Substring(@CSVDomainList,1,Charindex(@Delimiter, @CSVDomainList) - 1)))
		SET @CSVDomainList = Substring(@CSVDomainList, Charindex(@Delimiter, @CSVDomainList) + Len(@Delimiter), Len(@CSVDomainList))

		--Get Domain NC
		SELECT @DomainNamingContext = NcName FROM [ActiveDirectory].[dbo].[fn_GetDomains] (@CurrentDomain) Where DnsDomainName like @CurrentDomain

		--Build Select Statement
		SET @QueryString = @QueryString + 'SELECT '''
			+ @CurrentDomain
			+ ''' As DomainFqdn, * FROM [dbo].[fn_GetUserObjects]('''
			+ @CurrentDomain + ''', 389, '''
			+ @DomainNamingContext + ''', ''' + @LdapQueryFilter + ''', NULL) UNION '
	END
	
	SET @CurrentDomain = ltrim(rtrim(@CSVDomainList))
	--Get Domain NC
	SELECT @DomainNamingContext = NcName FROM [ActiveDirectory].[dbo].[fn_GetDomains] (@CurrentDomain) Where DnsDomainName like @CurrentDomain

	SET @QueryString = @QueryString + 'SELECT '''
		+ @CurrentDomain
		+ ''' As DomainFqdn, * FROM [dbo].[fn_GetUserObjects]('''
		+ @CurrentDomain + ''', 389, '''
		+ @DomainNamingContext + ''', ''' + @LdapQueryFilter + ''', NULL)'
	PRINT @QueryString
	EXEC [sys].[sp_executesql] @QueryString
END
